package com.demo.index;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.demo.common.model.Financial;
import com.demo.common.pojo.AjaxRtVO;
import com.demo.common.pojo.DataGridVO;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;

import java.math.BigDecimal;
import java.util.List;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * IndexController
 */
public class IndexController extends Controller {
	public void index() {
		render("index.html");
	}

	/**
	 * 重新计算
	 */
	public void recount() {
		String jsonString = HttpKit.readData(getRequest());
		if (StrUtil.isNotBlank(jsonString)) {
			Financial financial = JSON.parseObject(jsonString, Financial.class);
			BigDecimal salary = Convert.toBigDecimal(financial.getSalary(), BigDecimal.ZERO);
			BigDecimal housingLoan = Convert.toBigDecimal(financial.getHousingLoan(), BigDecimal.ZERO);
			BigDecimal creditCard = Convert.toBigDecimal(financial.getCreditCard(), BigDecimal.ZERO);
			BigDecimal otherCost = Convert.toBigDecimal(financial.getOtherCost(), BigDecimal.ZERO);
			/**
			 25% — 现金
			 10% — 保险
			 50% — 股票价值投资
			 15% — 高风险高收益
			 */
			BigDecimal disposableFunds = NumberUtil.sub(salary, housingLoan, creditCard, otherCost);
			BigDecimal cash = NumberUtil.mul(disposableFunds, 0.25);
			BigDecimal insurance = NumberUtil.mul(disposableFunds, 0.1);
			BigDecimal shares = NumberUtil.mul(disposableFunds, 0.5);
			BigDecimal highRisk = NumberUtil.mul(disposableFunds, 0.15);

			financial.setCash(cash);
			financial.setInsurance(insurance);
			financial.setShares(shares);
			financial.setHighRisk(highRisk);

			AjaxRtVO<Financial> rt = new AjaxRtVO<Financial>();
			rt.setData(financial);
			rt.setStatu(true);
			renderJson(rt);
			return;
		}
		renderNull();
	}

	/**
	 * 保存方法
	 */
	public void doSave () {
		AjaxRtVO<Financial> rt = new AjaxRtVO<Financial>();
		boolean result = true;
		String jsonString = HttpKit.readData(getRequest());
		if (StrUtil.isNotBlank(jsonString)) {
			Financial financial = JSON.parseObject(jsonString, Financial.class);
			if (financial != null) {
				if (financial.getId() != null) {
					result = financial.update();
				} else {
					result = financial.save();
				}
			}
		}
		rt.setStatu(result);
		if (!result) {
			rt.setErrMsg("编辑失败!");
		}
		renderJson(rt);
	}

    /**
     * 列表查询方法
     */
	public void list() {
		DataGridVO rtVO = new DataGridVO();
		List<Financial> searchResultList = Financial.dao.find("select * from financial order by days");
		rtVO.setTotal(searchResultList.size());
		rtVO.setRows(searchResultList);
		renderJson(rtVO);
	}

    /**
     * 根据id删除
     */
	public void deleteById() {
		Financial.dao.deleteById(getParaToInt());
		renderNull();
    }
}



